/* eslint-disable no-restricted-globals */
import React from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '@/assets/logo.png'
import styles from '@/pages/Login/index.module.scss'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions/login'
import { useHistory } from 'react-router'

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  let pathname = '/home'
  if (history.location.state) {
    pathname = history.location.state.from
  }
  console.log(history, 'history')
  const [loading, setLoading] = React.useState(false)
  const onFinish = async (values) => {
    setLoading(true)
    try {
      await dispatch(login(values))
      message.success('登录成功', 1, () => {
        history.replace(pathname)
      })
    } catch (e) {
      // 错误消息，持续展示1秒
      message.error(e.response.data.message, 1)
    } finally {
      setLoading(false)
    }
  }
  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          onFinish={onFinish}
          autoComplete="off"
          size="large"
          initialValues={{
            agree: true,
            mobile: '13911111111',
            code: '246810'
          }}
          validateTrigger="onBlur">
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号!' }, // 必须要填
              { pattern: /^1[3-9]\d{9}$/, message: '请输入合法的手机号!' }
            ]}>
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码!' }, // 必须要填
              { pattern: /^\d{6}$/, message: '请输入6位验证码!' }
            ]}>
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator (rule, value) {
                  if (value) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject(new Error('请阅读并同意协议'))
                  }
                }
              }
            ]}>
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
